var async = require('async');
var config = require('../../../config')
var AE = require("apiengine")({mode:config.dev,scope:'activity'});
var Q = require('q');
var AV = require('leanengine');
//用户个人中心

module.exports = {
    //首次登录，发放三张随机卡片
    give3Rewards:function(table,flow1,flow2,flow3){
        var deferred = Q.defer();
        var personalCenter1 = new AE.Object(table,flow1);
        var personalCenter2 = new AE.Object(table,flow2);
        var personalCenter3 = new AE.Object(table,flow3);
        var batch = new AE.Batch();
        batch.insert([personalCenter1,personalCenter2,personalCenter3]).then(function(data){
            console.log(data);
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },

    //首页显示：当前集齐人数，个人卡片情况
    showHomeCard:function(uid){
        uid = uid || '456' ;
        var deferred = Q.defer();
        var query = new AE.Query('lantern_personal_center');
        query.sort("id+");
        query.condition(" uid = '"+uid + "'");
        query.find().then(function(data){
            var cardInfo = {
                'lan1':{reward:1,number:0,reward_name:'豆沙元宵'},
                'lan2':{reward:2,number:0,reward_name:'黑芝麻元宵'},
                'lan3':{reward:3,number:0,reward_name:'鲜肉元宵'},
                'lan4':{reward:4,number:0,reward_name:'水果元宵'},
                'lan5':{reward:5,number:0,reward_name:'花生元宵'},
                'lan6':{reward:6,number:0,reward_name:'椰蓉元宵'}
            }
            if(data.get().length < 1){
                //没有
                deferred.resolve({code:1,cardInfo:JSON.stringify(cardInfo)})
            }else{
                for(var i in data.get()){
                    cardInfo['lan'+data.get()[i].reward].number =  data.get()[i].number ;
                    //cardInfo['lan'+data.get()[i].reward].reward_name =  data.get()[i].reward_name ;
                }
                deferred.resolve({code:0,cardInfo:JSON.stringify(cardInfo)})
            }
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //赠送卡片存入数据
    giveOrSeekCard:function(table,args){
        var deferred = Q.defer();
        var give_reward = new AE.Object(table);
        give_reward.set(args);
        give_reward.create().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //获取讨要或者赠送数据（打开分享链接时调用）
    getGiveOrSeekInfo:function(table,id){
        var deferred = Q.defer();
        var query = new AE.Object(table);
        query.getById(id).then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //扣减或者删除个人中心表中的奖品数量
    clearRewardInPersonal:function(uid,reward,number,reward_name){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_personal_center');
        //query.sort("id+");
        query.condition(" uid = '"+uid+"'");
        query.and(" reward = "+reward);
        query.and(" status = 1");
        query.first().then(function(data){
            if(data.get().id){
                var new_number = parseInt(data._d.number) + parseInt(Math.abs(number)) ;
                console.log(new_number);
                if(new_number < 0){
                    deferred.reject({code:-1,msg:'卡片数量不足'})
                }else{
                    data.set({number:new_number});
                    data.save().then(function(new_data){
                        deferred.resolve(new_data)
                    });
                }

            }else{
                //创建一条新数据
                var res = new AE.Object('lantern_personal_center');
                res.set({uid:uid,reward:reward, number:number,reward_name:reward_name});
                res.create().then(function(data){
                    deferred.resolve(data);
                }).catch(function(err){
                    deferred.reject({code:-1,msg:'网络异常'});
                });
            }

        }).catch(function(err){
            deferred.reject({code:-1,msg:'网络异常'})
        });
        return deferred.promise;
    },
    //插入中奖流水
    insertRewardFlow:function(args){
        var deferred = Q.defer();
        var personalCenter = new AE.Object('lantern_reward_flow');
        personalCenter.set(args);
        personalCenter.create().then(function(data){
            deferred.resolve(data);
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //获取leancloud中_User表中的数据（主要是point和余额）
    getUserFromAV:function(openid){
        var _User = AV.Object.extend('_User');
        var query = new AV.Query(_User);
        query.equalTo('openid',openid);
        return query.first()
    },
    //更新用户数据
    updateUserFromAV:function(uid) {
        var defer = Q.defer();
        async.waterfall([
            function(cb){
                var _User = AV.Object.extend('_User');
                var query = new AV.Query(_User);
                query.get(uid).then(function(data){
                    if(data.get('point')<20){
                        //积分不够，不能捞奖
                        cb({code:-1,msg:'积分不足'});
                    }else{
                        var point = data.get('point') - 20 ;
                        data.save({point:point}).then(function(){
                            cb(null, {code:0,user:data});
                        }).catch(function(err){
                            cb({code:-1,msg:'网络异常'});
                        });
                    }
                }).catch(function(){
                    cb({code:-1,msg:'网络异常'});
                });
            },function(res,cb){
                if(res.code === 0){
                    var user = res.user ;
                    //插入流水
                    var PointFlow = AV.Object.extend('PointFlow');
                    var pointFlow = new PointFlow();
                    pointFlow.save({
                        //new Date().getYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()
                        //content: new Date().toFormat("YYYY/MM/DD")+"闹元宵扣除积分-"+20,
                        content: new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()+"闹元宵扣除积分-"+20,
                        userid: uid,
                        newpoint: parseInt(-20),
                        beforepoint: user.get('point'),
                        afterpoint: parseInt(user.get('point')-20)
                    }, {
                        success: function(pointflow) {
                            cb(null,{code:0,msg:"扣减成功"});
                        },
                        error: function(pointflow, error) {
                            cb(null,{code:0,msg:"扣减成功,流水记录失败！"});
                        }
                    });
                }else{
                    cb({code:-1,msg:'网络异常'})
                }
            }
        ],function(err,result){
            if(err){
                defer.reject(err);
            }else{
                defer.resolve(result);
            }
        })

        return defer.promise;
    },
    //获取首页已集齐人数
    countHome:function(){
        var deferred = Q.defer();
        async.waterfall([
            function(cb){
                var query = new AE.Query('lantern_home');
                query.condition(" status = 1");
                query.count().then(function(data){
                    cb(null, data)
                })
            },function(count,cb){
                var query = new AE.Query('lantern_home_count');
                var base_count = 0 + count;
                query.first().then(function(data){
                    if(data.get('id')){
                        base_count = base_count + data.get('count');
                        cb(null, base_count);
                    }else{
                        cb(null, '计算中...');
                    }
                }).catch(function(err){
                    cb(null, '计算中...');
                });
            }
        ],function(err,result){
            if(err){
                deferred.reject(err)
            }else{
                deferred.resolve(result)
            }
        })

        return deferred.promise;
    },
    countHome1:function(){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_home_count');
        query.first().then(function(data){
            var base_count = data.get('count');
            deferred.resolve(base_count);
        }).catch(function(err){
            deferred.resolve(0);
        });
        return deferred.promise;
    },

    //获取当前时间所对应的奖池数据
    getRewardPool:function(){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_reward_pool');
        var now =  Date.parse(new Date());
        query.sort("objectId+");
        query.condition("startTime < '"+now +"'");
        query.and(" endTime > '"+now +"'");
        query.and(" number != 0 ");
        query.find().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //获取当前时间所对应的奖池数据
    getRewardPool1:function(){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_reward_pool');
        var now =  Date.parse(new Date());
        query.sort("objectId+");
        query.condition("startTime < '"+now +"'");
        query.and(" endTime > '"+now +"'");
        query.and(" objectId = 1");
        query.first().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    getCardFromPool:function(){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_reward_pool');
        var now =  Date.parse(new Date());
        query.sort("objectId+");
        query.condition("startTime <= '"+now +"'");
        query.and(" endTime >= '"+now +"'");
        query.and(" status = 1");
        //query.and(" number > 0");
        query.and(" rewardType = 1") ;
        query.find().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    getCardFromPool1:function(){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_reward_pool');
        var now =  Date.parse(new Date());
        query.sort("objectId+");
        query.condition("startTime < "+now +"");
        query.and(" endTime > "+now +"");
        query.and(" status = 1");
        //query.and(" number > 0");
        query.and(" rewardType = 1") ;
        query.and(" objectId !=4") ;
        query.and(" objectId != 6") ;

        query.find().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },


    getRewardPoolByReward:function(reward_id){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_reward_pool');
        query.condition(" objectId = "+reward_id);
        query.first().then(function(data){
            console.log(data);
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //根据id获取数据
    getInfoById:function(table,id){
        var deferred = Q.defer();
        var query = new AE.Object(table);
        query.getById(id).then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //更新数据
    updateById:function(table,id,args){
        var deferred = Q.defer();
        var query = new AE.Object(table);
        query.getById(id).then(function(data){
            if(data.get().uid){
                //已领取过
                deferred.reject({code:-1})
            }else{
                data.set(args);
                data.save().then(function(new_data){
                    deferred.resolve(new_data)
                }).catch(function(err){
                    deferred.reject(err)
                });
            }
        }).catch(function(err){
            deferred.reject({code:-1,msg:'网络异常'})
        });
        return deferred.promise;
    },
    updateInfo:function(table,args,condition){
        var deferred = Q.defer();
        var query = new AE.Query(table);
        query.condition(condition);
        query.first().then(function(data){
            if(data.objectId){
                data.save(args).then(function(new_data){
                    deferred.resolve(new_data)
                });
            }else{
                //创建一条新数据
                var personalCenter = new AE.Object(table);
                personalCenter.set(args);
                personalCenter.create().then(function(new_data){
                    deferred.resolve(new_data);
                });
            }
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //更新center表中的number或者创建一条新的记录
    updatePersonalCenter:function(uid,reward,number,reward_name){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_personal_center');
        query.condition(" uid = '"+uid+"' and  reward = "+reward +" and status = 1"); //用户id
        //query.condition(" reward = "+reward);   //奖品id
        //query.condition(" status = "+1);   //奖品id
        query.first().then(function(data){
            if(data._d.id){
                var new_number = parseInt(data._d.number)+parseInt(number);
                if(new_number < 0){
                    deferred.reject({code:-1,msg:'卡片数量不足'})
                }else{
                    data.set({number:new_number});
                    data.save().then(function(new_data){
                        deferred.resolve({code:0,data:new_data})
                    }).catch(function(err){
                        deferred.reject({code:-2,msg:'网络异常'})
                    });
                }
            }else{
                //创建一条新数据
                var personalCenter = new AE.Object('lantern_personal_center');
                personalCenter.set({uid:uid,reward:reward,status:1,number:1,reward_name:reward_name});
                personalCenter.create().then(function(new_data){
                    deferred.resolve({code:0,data:new_data})
                }).catch(function(err){
                    deferred.reject({code:-2,msg:'网络异常'})
                });
            }
        }).catch(function(err){
            deferred.reject({code:-2,msg:'网络异常'})
        });
        return deferred.promise;
    },
    countPersonalCenter:function(uid){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_personal_center');
        query.condition(" uid = '"+uid+"' and status = 1 and number>0"); //用户id
        query.count().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    countPersonalCenter1:function(uid){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_personal_center');
        query.condition(" uid = '"+uid+"' and status = 1 "); //用户id
        query.count().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },
    //创建或者更新lantern_home表
    updateHomeTable:function(uid,state){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_home');
        query.condition(" uid = '"+uid+"'"); //用户id
        query.first().then(function(data){
            var status = 0 ;
            if(state === "add"){
                status = 1 ;
            }
            if(data._d.id){
                data.save({status:status}).then(function(new_data){
                    deferred.resolve(new_data)
                });
            }else{
                //创建一条新数据
                var personalCenter = new AE.Object('lantern_home');
                personalCenter.set({uid:uid,status:status});
                personalCenter.create().then(function(new_data){
                    deferred.resolve(new_data);
                });
            }
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },

    //根据uid和rewardid到个人中心表中查找记录
    getCenterInfo:function(uid,rewardid){
        var deferred = Q.defer();
        var query = new AE.Query('lantern_personal_center');
        query.condition(" uid='"+uid+"'");
        query.and(" reward="+rewardid);
        query.first().then(function(data){
            deferred.resolve(data)
        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },

    //向seek表中插入数据
    insertSeek:function(args){
        var deferred = Q.defer();
        var seek = new AE.Object('lantern_seek_reward');
        seek.set(args);
        seek.create().then(function(data){
            deferred.resolve(data);
        }).catch(function(err){
            deferred.reject(err);
        });
        return deferred.promise;
    }

    ,

    //更新奖池信息
    updatePool:function(reward_id){
        var deferred = Q.defer();
        var query = new AE.Object("lantern_reward_pool");
        query.getById(reward_id).then(function(data){
            if(data.get('id')){
                if(data.get('number') === -1){
                    deferred.reject({code:0,msg:'奖池无需更新'})
                }else{
                    var new_number =data.get ('number')-1
                    if(data.get ('number') ===0){
                        deferred.reject({code:0,msg:'奖池无需更新'})
                    }else{
                        data.set({number:new_number})
                        data.save().then(function(){
                            deferred.resolve(data)
                        });
                    }

                }

            }else{
                deferred.reject({code:-1,msg:'奖池更新失败'})
            }

        }).catch(function(err){
            deferred.reject(err)
        });
        return deferred.promise;
    },


    /**
     * 最终奖品发放  start
     */
    getFinalResult:function(uid){

    },
    //获取最终的活动结果表lantern_personal_center_zsm
    getZSMInfo:function(uid){
        var q = Q.defer();
        var query = new AE.Query('lantern_personal_center_zsm');
        query.condition(" uid='"+uid+"'");
        query.first().then(function(data){
            if(data.get('id')){
                q.resolve({code:0,info:data.get()});
            }else{
                q.reject({code:-1,msg:'没有获取到获奖信息'})
            }
        });
        return q.promise;
    },
    //更新表lantern_personal_center_zsm
    updateZSMInfo:function(uid,args){
        var q = Q.defer();
        var query = new AE.Query('lantern_personal_center_zsm');
        query.condition(" uid='"+uid+"'");
        query.first().then(function(data){
            console.log(data.get().id);
            console.log(data.get('id'));
            if(data.get('id')){
                console.log('111111111');
                data.set(args);
                data.save().then(function(new_data){
                    console.log('222222222222');
                    q.resolve({code:0,info:new_data.get()});
                }).catch(function(err){
                    q.reject({code:-1,msg:'没有获取到获奖信息',err:err})
                });
            }else{
                console.log('=========');
                q.reject({code:-1,msg:'没有获取到获奖信息'})
            }
        });
        return q.promise;
    },

    //发放现金
    giveCash:function(uid,cash){
        var timestamp = Date.parse(new Date());
        var promise = new AV.Promise();
        var _User = AV.Object.extend('_User');
        var AmountFlow = AV.Object.extend('AmountFlow');
        async.waterfall([
            function(callback){
                var query = new AV.Query(_User);
                //query.equalTo("amount",'签到现金'+cash+'元');
                var newAmount = 0 ;
                var oldAmount = 0 ;
                query.get(uid).then(function(res){
                    if(res){
                        oldAmount = parseFloat(res.get('amount')) ;
                        newAmount = oldAmount+parseFloat(cash) ;
                        res.save({amount:newAmount}).then(function(){
                            callback(null,{user:res,newAmount:newAmount,oldAmount:oldAmount});
                        }).catch(function(err){
                            callback({code:-1,msg:'保存失败'});
                        });

                    }else{
                        callback({code:-1,msg:'用户不存在'});
                    }
                });
            },
            //发放现金
            function(res,callback){
                var amountFlow = new AmountFlow();
                amountFlow.save({
                    content: "闹元宵奖励现金充值+"+cash+"元",
                    userid:uid,
                    newamount: parseFloat(cash),
                    beforeamount: res.oldAmount,
                    afteramount:res.newAmount
                }, {
                    success: function(post) {
                        callback(null,{code:0,msg:"发放成功",res:res});
                    },
                    error: function(post, error) {
                        callback(null,{code:0,msg:"发放失败",res:res});
                    }
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /**
     * 最终奖品发放  end
     */
};